package it.uniroma2.controller;

import it.uniroma2.MonitorClient;
import it.uniroma2.cloud.PROVIDER;
import it.uniroma2.monitor.client.DateUtils;
import it.uniroma2.monitor.client.MetricRequest;
import it.uniroma2.monitor.client.MetricResult;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

public class LoadChecker {

	private MonitorClient monitorClient;
	private Timer timer;

	public LoadChecker() {
		this.monitorClient = MonitorClient.getInstance();
		scheduleTimerTasks(0);
	}

	private void scheduleTimerTasks(int secondsDelay) {
		timer = new Timer();
		timer.scheduleAtFixedRate(new LoadCheck(), secondsDelay * 1000L, // initial
				// delay
				10 * 1000);
	}

	class LoadCheck extends TimerTask {

		public void run() {
			System.out.println("-- Load Check: " + new Date());
			new Thread(new LoadCheckExecutor(PROVIDER.AWS_EC2)).start();
			new Thread(new LoadCheckExecutor(PROVIDER.OPENSTACK)).start();
		}
	}

	class LoadCheckExecutor implements Runnable {

		private PROVIDER provider;

		public LoadCheckExecutor(PROVIDER provider) {
			this.provider = provider;
		}

		@Override
		public void run() {
			DateTime until = new DateTime(DateTimeZone.UTC);
			DateTime from = DateUtils.lastMinutes(until, 2);
			String metricRequest = "movingAverage(post.aggregated."
					+ provider.name()
					+ ".imagetranscoder.monitor.load.loadAverage-1Min,5)";
			MetricRequest req = new MetricRequest(metricRequest, from, until);

			// obtain 4 data points each one representative of last 15 point

			MetricResult result = monitorClient.makeRequest(req);
			Double avg = result.avg();
			System.out
					.println(metricRequest + " [AVG on "
							+ result.size() + " results: " + avg);
			ReporterChecker.getInstance().setMovingAverage_1MinLoad(provider,
					avg);
			if (result.avg() > 0.9) {
				// Executors.newSingleThreadExecutor().execute(new Runnable() {
				// @Override
				// public void run() {
				timer.cancel();
				Controller.getInstance().addWorkerNode(provider, 1);
				scheduleTimerTasks(120);
				// }
				// });
			}
			// if(result.avg() > 0.2){
			// Executors.newSingleThreadExecutor().execute(new Runnable() {
			// @Override
			// public void run() {
			// Controller.getInstance().
			// .destroyWorkerNode(provider, ip);
			// Controller.getInstance()
			// .destroyWorkerNode(provider, ip);
			// }
			// });
			// }

		}
	}

	public static void main(String[] args) {
		new LoadChecker();
	}
}
